//
//  SLTabBar.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/19.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit

let buttonCount = 5 //5个按钮
class SLTabBar: UITabBar {
    
    //按钮点击的闭包
    var commposeClosure: (() -> ())?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = frame.width / CGFloat(buttonCount) //item的宽度
        
        // 计算最左边的这个frame,后面使用CGRectOffset
        let originFrame = CGRect(x: 0, y: 0, width: width, height: frame.height)
        
        var index = 0
        for view in subviews {
            if view.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置每个UITabBarButton的位置
//                view.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: frame.height)
                
                view.frame = CGRectOffset(originFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
                //或者
//                index++
//                if index == 2 {
//                    index++
//                }
            }

        }
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.height)
    }
    lazy var composeButton: UIButton = {
       let button = UIButton()
        
        //添加背景图
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
         button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        self.addSubview(button)
        
        //按钮的点击事件
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    //点击按钮触发
    func composeClick() {
        //调用闭包
        commposeClosure?()
    }
}
